//
//  HELCompulsoryVC.m
//  sanda
//
//  Created by 陈武琦 on 16/7/12.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELDownloadVC.h"
#import "HELCompulsoryCell.h"
#import "HELUserInfoM.h"
#import "HELCourseDetailVC.h"
#import "Masonry.h"
#import "HELSuperTableView.h"
#import "CWQ_tableView.h"
#import "BTCollectionBottomMenuView.h"
#import "ReaderFileViewController.h"
#import "ReamlDataTool.h"
#import "HELPDFfileCacheTool.h"
@interface HELDownloadVC ()<UITableViewDelegate,BTCollectionBottomMenuViewViewDelegate>
@property(nonatomic, copy)NSArray* dataSource;

@property(nonatomic, strong)CWQ_tableView *tableView;
@property(nonatomic, strong)BTCollectionBottomMenuView *bottomMenu;
@property (nonatomic, copy) NSMutableDictionary *deleteDic;
//加载的页面
@property (nonatomic, assign) NSInteger page;

@end
static NSString *cellID = @"HELCompulsoryCellID";

@implementation HELDownloadVC


- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self titleView:self.title];
    self.view.backgroundColor = [UIColor  whiteColor];
    [self setupSubviews];
    
}

- (void)setupSubviews {
    CWQ_tableView *tableView = [[CWQ_tableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 108) style:UITableViewStylePlain cellClass:@"HELCompulsoryCell" vc:self upload:YES];
    [self.view addSubview:tableView];
    _tableView = tableView;
    _dataSource = [[NSArray alloc] init];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];

    UIButton *rightItemBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightItemBtn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
    rightItemBtn.titleLabel.font = [UIFont systemFontOfSize:16];

    [rightItemBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightItemBtn]];
    defineWeakSelf;
    [self.bottomMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
        make.left.equalTo(weakSelf.view).with.offset(0);
        make.top.equalTo(weakSelf.tableView.mas_bottom).with.offset(0);
        
    }];
    
    /*
    RLMRealm *realm = [RLMRealm defaultRealm]; // Create realm pointing to default file
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
   
    
        [realm beginWriteTransaction];
        NSString *icon = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1473041357&di=124e43ce7e16f17cebc3a6143ff11dea&src=http://b.hiphotos.baidu.com/image/pic/item/d009b3de9c82d15825ffd75c840a19d8bd3e42da.jpg";
        for (int i = 0; i < 50; i++) {
            NSDictionary *dict = @{@"id":@(i), @"name":[NSString stringWithFormat:@"%d%d%d%d%d%d%d",i,i,i,i,i,i,i], @"attachUrlMap":@{@"mid":icon}, @"date":[NSString stringWithFormat:@"%d天后过期",i], @"persent":[NSString stringWithFormat:@"%d0%@",i, @"%"]};
            HELCompulsoryM *model = [HELCompulsoryM mj_objectWithKeyValues:dict];
            
            [realm addObject:model];
            
        }
        [realm commitWriteTransaction];
       // dispatch_async(dispatch_get_main_queue(), ^{
            
     
     [self.tableView cwq_requestDataWithDown:YES];
//        });
//    });

*/
    [self.tableView cwq_requestDataWithDown:YES];

}

- (void)deleteClick:(UIButton *)btn {

    self.tableView.editing = !self.tableView.editing;
    if (self.tableView.editing) {
        [btn setImage:nil forState:UIControlStateNormal];
        [btn setTitle:@"取消" forState:UIControlStateNormal];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 44, 0));
        }];
    }else {
        
        [btn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        [btn setTitle:@"" forState:UIControlStateNormal];
        [self.deleteDic removeAllObjects];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
}


- (BTCollectionBottomMenuView *)bottomMenu {
    if (!_bottomMenu) {
        _bottomMenu = [BTCollectionBottomMenuView menuView];
        _bottomMenu.delegate = self;
        [self.view addSubview:_bottomMenu];
    }
    
    return _bottomMenu;
    
}


- (void)setDataSource:(NSArray *)dataSource {
    _dataSource = dataSource;
    [self.tableView setupSourceArray:dataSource];
}

- (NSMutableDictionary *)deleteDic {
    
    if (!_deleteDic) {
        _deleteDic = [@{} mutableCopy];
    }
    
    return _deleteDic;
}


- (void)cwq_tableView:(CWQ_tableView *)tableView requestDataWithDown:(BOOL)down {
    NSInteger count;
    if (down) {
        count = 10;
//        self.page = 1;
    }else {
//        self.page++;
        count = self.dataSource.count + 10;
        
    }
    /*
     *取数据
     */
//    NSPredicate *pred = [NSPredicate predicateWithFormat:@"id BETWEEN %@", @[@(10*(self.page-1)), @(count-1)]];
    //RLMResults *array = [HELCompulsoryM objectsWithPredicate:pred];
       NSLog(@"_________%@",[NSThread currentThread]);
    RLMResults *array = [[ReamlDataTool sharedTool] allObjects];
    
    
    
    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        RLMRealm *otherRealm = [RLMRealm defaultRealm];
        
        
//            dispatch_async(dispatch_get_main_queue(), ^{

            if (down) {
                NSMutableArray *mua = [NSMutableArray array];
                NSInteger realCount = array.count > count? count:array.count;
                
                for (int i = 0; i < realCount; i++) {
                    
                    id obj = array[i];
                    [mua addObject:obj];
                }
                
                self.dataSource = [mua copy];
                [self.tableView.header endRefreshing];
                if (count >= array.count) {
                  [self.tableView.footer noticeNoMoreData];
                }else {
                    [self.tableView.footer resetNoMoreData];
                }
                
            }else {
                NSMutableArray *mua = [@[] mutableCopy];
                [self.tableView.footer endRefreshing];
                if (array.count <= count) {
                    for (id obj in array) {
                        [mua addObject:obj];
                    }
                    [self.tableView.footer noticeNoMoreData];
                }else {
                    
                    for (int i = 0; i < count; i++) {
                        id obj = array[i];
                        [mua addObject:obj];
                    }
                }
                self.dataSource = [mua copy];
        }
//        });
//    });

}


#pragma mark - <UITableViewData and UITableDelegate>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HELCompulsoryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    HELCompulsoryM *model = self.dataSource[indexPath.row];
    cell.model = model;
    [cell fromDownload];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.editing) {
        HELCompulsoryM *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic setObject:model forKey:[@(model.id) stringValue]];
        [self resetDeleteBtnTitle];
        return;
    }
    
    HELCompulsoryM *model = self.dataSource[indexPath.row];
//    HELNetworkStatus state = [HELNetworkManager sharedMg].netStatus;
//    if (state == 0) {
    
        ReaderFileViewController *fileViewController = [[ReaderFileViewController alloc] init];
        //
        
        fileViewController.title = model.name;
//        fileViewController.urlStr =self.courseModel.pdfNameShow;
        fileViewController.courseId = model.id;
        fileViewController.pdfName = model.pdfName;
        fileViewController.modalPresentationStyle = UIModalPresentationFullScreen;
        fileViewController.isFromMyDownload =YES;
        defineWeakSelf;
        fileViewController.callBack = ^(){
            
//            [weakSelf requesetSdutyDetailData];
            
            
        };
        
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fileViewController];
        [navigationController.navigationBar setTintColor:[UIColor whiteColor]];
        
        navigationController.navigationBar.translucent = YES;
        
        [self presentViewController:navigationController animated:YES completion:NULL];
        
//        return;
//    }
//    
//
//     HELCourseDetailVC *courseDetailVC = [HELCourseDetailVC new];
//     weakSelf_define;
//     courseDetailVC.courseId = model.id;
//    courseDetailVC.callBack = ^(HELCourseDetailModel *model){
//        [weakSelf.tableView cwq_requestDataWithDown:YES];
//    };
//    
//     [self.navigationController pushViewController:courseDetailVC animated:YES];
}

- (void)resetDeleteBtnTitle {
    
    NSString *deleTitle;
    if ([self.deleteDic count] == 0) {
        deleTitle = @"删除";
    }else {
        
        deleTitle = [NSString stringWithFormat:@"删除(%lu)",(unsigned long)[self.deleteDic count]];
    }
    [self.bottomMenu.deleteBtn setTitle:deleTitle forState:UIControlStateNormal];
    
}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        HELCompulsoryM *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic removeObjectForKey:[@(model.id) stringValue]];
        [self resetDeleteBtnTitle];

    }
}

#pragma mark ----------------bottomMenu代理--------------------------
- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickSelectBtn:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"全选"]) {
        [button setTitle:@"全不选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            HELCompulsoryM *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic setObject:model forKey:[@(model.id) stringValue]];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:NO];
            
        }
       
    }else {
        [button setTitle:@"全选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            HELCompulsoryM *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic removeObjectForKey:[@(model.id) stringValue]];
            [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
            
        }
    }
    [self resetDeleteBtnTitle];
}

- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickDeleteBtn:(UIButton *)button {
   
    //删除数据库中对应的数据
  
    NSArray *models = [self.deleteDic allValues];
   
    NSMutableArray *pdfNames =[NSMutableArray array];
    [models enumerateObjectsUsingBlock:^(HELCompulsoryM  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [pdfNames addObject:obj.pdfName];
    }];
    
    [[ReamlDataTool sharedTool] deleCourseWithCourses:[self.deleteDic allValues]];
    [HELPDFfileCacheTool removePdfFileWithPdfNames:pdfNames];
    ;
    if ([self.deleteDic count] == self.dataSource.count) {
       
        [self.deleteDic removeAllObjects];
        self.dataSource = @[];
        [button setTitle:@"删除" forState:UIControlStateNormal];
        return;
    }
    
    NSMutableArray *muA = [NSMutableArray arrayWithArray:self.dataSource];
    [muA removeObjectsInArray:[self.deleteDic allValues]];
    [self.deleteDic removeAllObjects];
    self.dataSource = [muA copy];
    [button setTitle:@"删除" forState:UIControlStateNormal];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
